﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using AnyOffice.DAL;
using AnyOffice.Components;
using AnyOffice.Appcode;

namespace AnyOffice.Web.general.system.netshareMagerGX
{
    public partial class filemove : BasePage
    {
        private DiskGXDao bllDisk = new DiskGXDao();//网络硬盘业务处理对象
        private DiskTypeGXDao bllDiskType = new DiskTypeGXDao();//网络硬盘类型业务处理对象

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["str"] != "")
                {
                    hidFileIds.Value = Request.QueryString["str"];
                    Bind(this.tree_MovePath.Nodes);
                }
            }
        }

        /// <summary>
        /// 节点绑定
        /// </summary>
        /// <param name="Nds">对象集合</param>
        public void Bind(TreeNodeCollection Nds)
        {
            string id = Session["mangerid"].ToString().Trim(',');
            string[] idarr = id.Split(',');
            for (int i = 0; i < idarr.Count(); i++)
            {
                List<AnyOffice.Model.DiskGX> disk = bllDisk.GetListByparentId(base.Conn, " DiskID =" + idarr[i] + " order by Seq");
                foreach (Model.DiskGX d in disk)
                {
                    TreeNode pnode = new TreeNode();
                    pnode.Value = d.DiskID.ToString();
                    pnode.Text = "<span style='cursor:hand' id='" + pnode.Value + "' onclick=\"SetNode('" + pnode.Value + "')\">" + d.Name + "</span>";
                    pnode.SelectAction = TreeNodeSelectAction.None;
                    pnode.ImageUrl = "/images/files/folder.gif";
                    Nds.Add(pnode);
                    Bindtree(pnode.ChildNodes, d.DiskID.ToString(), d.DiskTypeID.ToString());
                }
            }
        }

        /// <summary>
        /// 节点绑定
        /// </summary>
        /// <param name="Nds">对象集合</param>
        /// <param name="pid">父节点</param>
        /// <param name="dtype">硬盘类型</param>
        public void Bindtree(TreeNodeCollection Nds, string pid, string dtype)
        {
            List<AnyOffice.Model.DiskGX> diskList = bllDisk.GetListByparentId(base.Conn, " ParentDiskID=" + pid + " and FileTypeID=1 and DiskTypeID=" + dtype);
            foreach (Model.DiskGX disk in diskList)
            {
                TreeNode pnode = new TreeNode();
                pnode.Value = disk.DiskID.ToString();
                pnode.Text = "<span style='cursor:hand' id='" + pnode.Value + "' onclick=\"SetNode('" + pnode.Value + "')\">" + disk.Name + "</span>";
                pnode.SelectAction = TreeNodeSelectAction.None;
                pnode.ImageUrl = "/images/files/folder.gif";
                Nds.Add(pnode);
                Bindtree(pnode.ChildNodes, pnode.Value, dtype);
            } tree_MovePath.ExpandDepth = 1;
        }


        /// <summary>
        ///  移动 click
        /// </summary>
        protected void btn_MovePath_Click(object sender, EventArgs e)
        {
            string fileId = this.hidFileIds.Value.Trim(',');
            string[] fileIdList = fileId.Split(',');
            if (treeSelecteid.Value == "")
            {
                MessageBox.Show(this, "请选择移动到的目录！");
                return;
            }
            if (fileIdList.Contains(treeSelecteid.Value))
            {
                MessageBox.Show(this, "不允许将一个目录移动到它的子目录下！");
            }
            else
            {
                if (!Public_foldGX.PathIsExist(fileId, treeSelecteid.Value))
                {
                    if (Public_foldGX.MapPathMove(fileId, treeSelecteid.Value)) //物理移动是否成功
                    {
                        bllDisk.UpdateParentId(base.Conn, treeSelecteid.Value, fileId);
                    }
                    MessageBox.ShowMsgScript(this, "移动成功！", "opener.document.location='Public_folder.aspx?pid=" + treeSelecteid.Value + "';window.close();");
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>if(window.confirm('当前文件夹中已存在该文件（夹），确定要覆盖吗？')){document.getElementById('btnHidden').click();}</script>");
                }
            }
        }

        /// <summary>
        /// 确定覆盖
        /// </summary>
        protected void btnHidden_Click(object sender, EventArgs e)
        {
            try
            {
                string fileId = this.hidFileIds.Value.Trim(',');
                string[] tel = fileId.Split(',');
                for (int i = 0; i < tel.Length; i++)
                {
                    if (Public_foldGX.MapPathMove(fileId, treeSelecteid.Value))
                    {
                        MapPathMoveDB(treeSelecteid.Value, tel[i].ToString());
                    }
                }
                MessageBox.ShowMsgScript(this, "移动成功", "opener.document.location='Public_folder.aspx?pid=" + treeSelecteid.Value + "';window.close();");
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }

        /// <summary>
        /// 文件移动
        /// </summary>
        /// <param name="strid">移动的id</param>
        /// <param name="npath">移动到得路径</param>
        public void MapPathMoveDB(string newid, string fileId)
        {
            try
            {
                //根据id获得文件（夹）名
                string oldfileName = bllDisk.GetFileName(base.Conn, fileId);
                //获得子节点集合
                DataTable dt = bllDisk.GetChildFileInfo(base.Conn, newid);
                if (dt.Rows.Count > 0)
                {
                    bool issame = true;
                    string sameDiskID = String.Empty;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (oldfileName.Equals(dt.Rows[i]["Name"].ToString()))
                        {
                            issame = true;
                            sameDiskID = dt.Rows[i]["DiskID"].ToString();
                            break;
                        }
                        else
                        {
                            issame = false;
                            bllDisk.UpdateParentId(base.Conn, treeSelecteid.Value, fileId);
                            bllDisk.Delete(base.Conn, int.Parse(fileId));
                        }
                    }
                    if (issame)
                    {
                        MapPathMoveDBSame(sameDiskID, fileId);
                        bllDisk.Delete(base.Conn, int.Parse(fileId));
                    }
                }
                else
                {
                    bllDisk.UpdateParentId(base.Conn, treeSelecteid.Value, fileId);
                    bllDisk.Delete(base.Conn, int.Parse(fileId));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }

        /// <summary>
        /// 文件移动
        /// </summary>
        /// <param name="strid">移动的id</param>
        /// <param name="npath">移动到得路径</param>
        public void MapPathMoveDBSame(string newid, string fileId)
        {
            try
            {
                DiskGXDao disk = new DiskGXDao();

                DataTable dtnew = new DataTable();

                dtnew = disk.GetChildFile(base.Conn, newid);

                DataTable dtold = new DataTable();

                dtold = disk.GetChildFile(base.Conn, fileId);

                for (int i = 0; i < dtold.Rows.Count; i++)
                {
                    if (!dtold.Rows[i]["FileTypeID"].ToString().Equals("1"))
                    {
                        //如果存在相同的文件，删除原来的文件数据，如果没有重名则更新父节点
                        if (isExistSameName(dtold.Rows[i]["Name"].ToString(), dtnew, 0))
                        {
                            bllDisk.Delete(base.Conn, int.Parse(dtold.Rows[i]["Name"].ToString()));
                        }
                        else
                        {
                            bllDisk.UpdateParentId(base.Conn, newid, dtold.Rows[i]["DiskID"].ToString());
                        }
                    }
                    else
                    {
                        if (isExistSameName(dtold.Rows[i]["Name"].ToString(), dtnew, 1))
                        {
                            string cnewid = SameName(dtold.Rows[i]["Name"].ToString(), dtnew);
                            if (String.IsNullOrEmpty(cnewid))
                            {
                                MapPathMoveDBSame(cnewid, fileId);
                            }
                        }
                        else
                        {
                            bllDisk.UpdateParentId(base.Conn, newid, dtold.Rows[i]["DiskID"].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
        }



        /// <summary>
        /// 判断文件是否重名
        /// </summary>
        /// <param name="newName">新名称</param>
        /// <param name="dt">数据集</param>
        public bool isExistSameName(string newName, DataTable dt, int type)
        {
            bool issam = false;
            if (type.Equals(0))
            {

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (!dt.Rows[i]["FileTypeID"].ToString().Equals("1"))
                    {
                        if (newName.Equals(dt.Rows[i]["Name"].ToString()))
                        {
                            issam = true;

                            break;
                        }
                        else
                        {
                            issam = false;
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["FileTypeID"].ToString().Equals("1"))
                    {
                        if (newName.Equals(dt.Rows[i]["Name"].ToString()))
                        {
                            issam = true;
                            break;
                        }
                        else
                        {
                            issam = false;
                        }
                    }
                }
            }
            return issam;
        }


        /// <summary>
        /// 判断文件是否重名
        /// </summary>
        /// <param name="newName">新名称</param>
        /// <param name="dt">数据集</param>
        public string SameName(string newName, DataTable dt)
        {
            string nameid = String.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (newName.Equals(dt.Rows[i]["Name"].ToString()))
                {
                    nameid = dt.Rows[i]["DiskID"].ToString();
                }
            }

            return nameid;
        }



    }
}